﻿using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;
using System;

namespace dIRca.Extras.Services
{
    public class Screenshots
    {
        public FrameworkElement FrameworkElement { get; set; }
        public string Title { get; set; }

        public Screenshots(FrameworkElement frameworkElement, string title)
        {
            FrameworkElement = frameworkElement;
            Title = title;
            Title = Title + " " + DateTime.Now.ToShortDateString();
        }

        public void Save()
        {
            try
            {
                var bmp = new WriteableBitmap(FrameworkElement, null);

                var ms = new MemoryStream();
                bmp.SaveJpeg(
                    ms,
                    (int)FrameworkElement.ActualWidth,
                    (int)FrameworkElement.ActualHeight,
                    0,
                    100);
                ms.Seek(0, SeekOrigin.Begin);

                var lib = new MediaLibrary();
                var filePath = string.Format(Title + ".jpg");
                lib.SavePicture(filePath, ms);

                MessageBox.Show(
                    "Saved in your media library!",
                    "Done",
                    MessageBoxButton.OK);
            }
            catch
            {
                MessageBox.Show(
                    "There was an error. Please disconnect your phone from the computer before saving.",
                    "Cannot save",
                    MessageBoxButton.OK);
            }
        }
    }
}
